// 简单的翻译系统
import zh_CN_common from './dev/locales/zh_CN/common/common.json'
import zh_CN_assets from './dev/locales/zh_CN/assets/assets.json'
import en_US_common from './dev/locales/en_US/common/common.json'
import en_US_assets from './dev/locales/en_US/assets/assets.json'

// 类型定义
interface TranslationResource {
  [key: string]: string | TranslationResource
}

interface Translations {
  [language: string]: {
    common: TranslationResource
    assets: TranslationResource
  }
}

type SupportedLanguage = 'zh-CN' | 'en-US'

// 翻译资源
const translations: Translations = {
  'zh-CN': {
    common: zh_CN_common as TranslationResource,
    assets: zh_CN_assets as TranslationResource
  },
  'en-US': {
    common: en_US_common as TranslationResource,
    assets: en_US_assets as TranslationResource
  }
}

// 语言映射函数
function normalizeLanguage(lang: string | null): SupportedLanguage {
  if (!lang) return 'zh-CN'

  // 处理语言代码映射
  const languageMap: Record<string, SupportedLanguage> = {
    'zh': 'zh-CN',
    'zh-cn': 'zh-CN',
    'zh-CN': 'zh-CN',
    'en': 'en-US',
    'en-us': 'en-US',
    'en-US': 'en-US'
  }

  return languageMap[lang] || 'zh-CN'
}

// 当前语言
let currentLanguage: SupportedLanguage = normalizeLanguage(localStorage.getItem('i18nextLng'))

// 初始化状态
let isInitialized = false

// 初始化函数
function initialize(): boolean {
  if (!isInitialized) {
    // 确保翻译资源已加载
    if (translations[currentLanguage]) {
      isInitialized = true
    } else {
      console.error('❌ 翻译系统初始化失败 - 未找到当前语言的翻译资源')
      console.log('期望语言:', currentLanguage)
      console.log('可用语言:', Object.keys(translations))
    }
  }
  return isInitialized
}

// 设置语言
export function setLanguage(lang: string): Promise<void> {
  const normalizedLang = normalizeLanguage(lang)
  currentLanguage = normalizedLang
  localStorage.setItem('i18nextLng', normalizedLang)
  return Promise.resolve() // 兼容异步调用
}

// 获取当前语言
export function getCurrentLanguage(): SupportedLanguage {
  return currentLanguage
}

// 翻译函数
export function t(key: string): string {
  // 确保初始化
  if (!initialize()) {
    return key
  }

  const parts = key.split('.')
  const translation = translations[currentLanguage]

  if (!translation) {
    console.error(`❌ 未找到语言 ${currentLanguage} 的翻译资源`)
    return key
  }

  // 处理嵌套键，如 assets.navigation.dashboard
  let result: TranslationResource | string = translation

  for (let i = 0; i < parts.length; i++) {
    const part = parts[i]

    if (result && typeof result === 'object' && part in result) {
      result = result[part]
    } else {
      return key
    }
  }

  if (typeof result === 'string') {
    return result
  } else {
    return key
  }
}

// 立即初始化
initialize()
